package com.snap.vseries.chart;


import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.MPPointF;
import com.snap.vseries.R;

import java.text.DecimalFormat;

public class MyMarkerView extends MarkerView {

    private TextView tv1;
    private TextView tv2;
    private LinearLayout ll;
    private View indicator;
    private int type;
    private int[] bgs = {R.drawable.bg_channel_unsel, R.drawable.bg_channel1, R.drawable.bg_channel2, R.drawable.bg_channel3, R.drawable.bg_channel4};
    private int[] indicators = {0, R.drawable.oval_ch1, R.drawable.oval_ch2, R.drawable.oval_ch3, R.drawable.oval_ch4};
    private DecimalFormat format;
    private LineData data;
    private int channelIndex;

    public MyMarkerView(Context context, int layoutResource, int type) {
        super(context, layoutResource);
        tv1 = findViewById(R.id.tv1);
        tv2 = findViewById(R.id.tv2);
        ll = findViewById(R.id.ll);
        indicator = findViewById(R.id.indicator);
        this.type = type;
        this.format = new DecimalFormat(type == 0 ? "#.##" : "#.###");
    }

    @Override
    public void refreshContent(Entry e, Highlight highlight) {
        Bundle b = (Bundle) e.getData();
        channelIndex = b == null ? 0 : b.getInt("channelIndex");
        ll.setBackgroundResource(bgs[channelIndex]);
        indicator.setBackgroundResource(indicators[channelIndex]);
        tv1.setText("荧光值");
        tv2.setText(String.format("%s: %s", type == 0 ? "Rn" : "△Rn", format.format(e.getY())));
        super.refreshContent(e, highlight);
    }

    @Override
    public MPPointF getOffset() {
        return new MPPointF(-(getWidth() / 2), -getHeight() + 3);
    }

    public void update(LineData data) {
        this.data = data;
    }

    @Override
    public void draw(Canvas canvas, float posX, float posY) {
        if (data != null) {
            ILineDataSet lineDataSet = data.getDataSetByIndex(channelIndex - 1);
            if (!lineDataSet.isVisible()) {
                return;
            }
        }
        MPPointF offset = getOffsetForDrawingAtPoint(posX, posY);

        int saveId = canvas.save();
        canvas.translate(posX + offset.x, posY + offset.y);
        draw(canvas);
        canvas.restoreToCount(saveId);
    }
}
